<?php

namespace app\adminapi\controller;

use app\helpers\Common;
use app\common\model\VueAdmin as Admin;

use think\facade\Db;
use think\facade\Cache;
use think\Exception;
use think\Request;
use app\BaseController;

class Auth extends BaseController
{
    /**
     * Login
     */
    public function login(Request $request)
    {
        try {
            $code = config('constants.STATUS_SUCCESS');
            $msg = '登录成功';

            if ($request->isPost()) {
                $param = $request->param();
                $username = trim($param['username']);
                $password = trim($param['password']);
                $remember = $param['remember'] ?? 0;
                $captcha_code = $param['captcha_code'] ?? '';
                $captcha_key = $param['captcha_key'] ?? '';

                if (!$username) {
                    throw new Exception('登录名不能为空！');
                }
                if (!$password) {
                    throw new Exception('密码不能为空！');
                }

                $where = [
                    'username' => $username,
                ];
                $adminInfo = Admin::where($where)->field('*')->find();
                if (!$adminInfo) {
                    throw new Exception('您的用户名不存在！');
                }
                if (!password_verify($password, $adminInfo['password'])) {
                    throw new Exception('密码错误！');
                }
                $captcha_code = trim($captcha_code);
                if ($captcha_code) {
                    $verifyObj = new \app\common\service\Verify();
                    if (!$verifyObj->check($captcha_code, $captcha_key)) {
                        throw new Exception('验证码错误！');
                    }
                }

                $adminInfo = Admin::formatItem($adminInfo);
                $token = md5(time() . uniqid() . mt_rand(1000, 9999));
                $token_expire = time() + 3600 * 6;
                // 记住密码
                if ($remember) {
                    $token_expire = time() + 3600 * 24 * 7;
                }
                /*
                $origin = $request->header('origin');
                if (strstr($origin, 'http://127.0.0.1') !== false || strstr($origin, 'http://localhost')) {
                    // 跨域不能用session(跨域sessionid每次都会变，不能用session)
                    // 记录登录时间及IP等信息
                    $data = [
                        'last_login_time' => time(),
                        'last_login_ip' => get_IP(),
                        'token' => $token,
                        'token_expire' => $token_expire
                    ];
                    $record = Admin::where('id', $adminInfo['id'])->update($data);
                    if (!$record) {
                        throw new Exception('服务异常，请重新登录！');
                    }
                } else {
                    $adminInfo['token'] = $token;
                    $adminInfo['token_expire'] = $token_expire;
                    session('admin', $adminInfo); //
                    if ($remember) {
                        cookie('admin', json_encode($adminInfo), $token_expire);
                    }
                }
                */
                //$adminInfo = json_decode(json_encode($adminInfo), true);
                $adminInfo = $adminInfo->toArray();
                $jwt_data = [
                    'admin_id' => $adminInfo['id'],
                    'login_time' => time(),
                    'login_ip' => get_IP(),
                ];
                $jwt_token = \app\common\service\AuthToken::create($jwt_data, $token_expire);
                //$adminInfo['auth_token'] = $jwt_token;
                // 记录登录时间及IP等信息
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_IP(),
                    'token' => $token,
                    'token_expire' => $token_expire
                ];
                $record = Admin::where('id', $adminInfo['id'])->update($data);
                if (!$record) {
                    throw new Exception('服务异常，请重新登录！');
                }
                // TODO 用cache保存，不能实现多人登录同一个账号（退出时会清空缓存），直接用JWT也是可行的
                // 用缓存保存登录信息
                cache('auth_admin_id-' . $adminInfo['id'], $adminInfo, $token_expire, 'admin-auth');

                // 日志
                $logRes = Common::actionLog($request, $adminInfo['id'], '管理员登录', 0, json_encode([$adminInfo]));
            } else {
                throw new Exception('请求方式不正确');
            }
        } catch (Exception $e) {
            $code = config('constants.STATUS_ERROR');
            $msg = $e->getMessage();
        }

        return api_response($code, $msg, [
            //'token' => $token ?? ''
            'token' => $jwt_token ?? '',
        ]);
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        $token = $request->param('token');
        $data = [
            'token' => '',
            'token_expire' => 0
        ];
        $result = Admin::where('token', $token)->update($data);
        if ($result === false) {
            return api_response(config('constants.STATUS_ERROR'), 'Error', []);
        }

        //session('admin', null);
        //cookie('admin', null);
        Cache::tag('admin-auth')->clear();

        Cache::tag('admin')->clear();

        return api_response(config('constants.STATUS_SUCCESS'), '', []);
    }
}
